package com.sinosoft.cloud.access.router;

import com.sinosoft.cloud.access.entity.TranData;
import com.sinosoft.cloud.common.SpringContextUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017-12-21.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RouterServiceImpl implements Router {

    private final Log logger = LogFactory.getLog(getClass());

    private Boolean needRouter = false;
    private String accessName;

    /**
     * 进行路由处理
     *
     * @param tranData
     * @return
     */
    @Override
    public boolean msgRouter(TranData tranData) {
        /*获取路由规则*/
        RouterBean routerBean = SpringContextUtils.getBeanByClass(RouterBean.class);

        if (routerBean != null) {
            if (routerBean.isHeadRemote(getAccessName(), tranData.getHead())) {
                setNeedRouter(true);
                logger.info("符合服务路由HeadEL校验逻辑，需要转发到CIP");
                return true;
            }
            if (routerBean.isBodyRemote(getAccessName(), tranData.getBody())) {
                setNeedRouter(true);
                logger.info("符合服务路由BodyEL校验逻辑，需要转发到CIP");
                return true;
            }
            if (routerBean.isCrossRemote(getAccessName(), tranData)) {
                setNeedRouter(true);
                logger.info("符合服务路由CrossEL校验逻辑，需要转发到CIP");
                return true;
            }
        }
        routerBean.setRouterKey(tranData.getHead().getTranNo());

        return false;
    }

    @Override
    public void setAcceessName(String acceessName) {
        this.accessName = acceessName;
    }

    public String getAccessName() {
        return accessName;
    }

    public Boolean getNeedRouter() {
        return needRouter;
    }

    public void setNeedRouter(Boolean needRouter) {
        this.needRouter = needRouter;
    }
}
